package com.ruoyi.web.controller.system;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.vo.ConsumptionRecordVo;
import com.ruoyi.system.domain.vo.ItemVo;
import com.ruoyi.system.domain.vo.ServiceItemTotalPriceVo;
import com.ruoyi.system.service.IGuestService;
import com.ruoyi.system.service.IRoomService;
import com.ruoyi.system.service.IServiceItemService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.service.IConsumptionRecordService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

import javax.annotation.Resource;

/**
 * 消费记录Controller
 * 
 * @author 华馨悦
 * @date 2025-01-24
 */
@Controller
@RequestMapping("/system/consumption")
public class ConsumptionRecordController extends BaseController
{
    private String prefix = "system/consumption";

    @Autowired
    private IConsumptionRecordService consumptionRecordService;

    @Resource
    private IRoomService roomService;

    @Resource
    private IServiceItemService serviceItemService;

    @Autowired
    private IGuestService guestService;


    @RequiresPermissions("system:consumption:view")
    @GetMapping()
    public String record(ModelMap mmap)
    {
        mmap.put("items", serviceItemService.selectServiceItemList(new ServiceItem()));
        mmap.put("rooms", roomService.selectRoomList(new Room()));
        return prefix + "/consumption";
    }

    /**
     * 查询消费记录列表
     */
    @RequiresPermissions("system:consumption:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(ConsumptionRecord consumptionRecord)
    {
        startPage();
        List<ConsumptionRecord> list = consumptionRecordService.selectConsumptionRecordList(consumptionRecord);
        List<ConsumptionRecordVo> consumptionRecordVos = new ArrayList<>();
        list.forEach(i -> {
            Long roomId = i.getRoomId();
            Long serviceItemId = i.getServiceItemId();
            Room room = roomService.selectRoomById(roomId);
            ServiceItem serviceItem = serviceItemService.selectServiceItemById(serviceItemId);
            ConsumptionRecordVo consumptionRecordVo = new ConsumptionRecordVo();
            BeanUtils.copyProperties(i, consumptionRecordVo);
            consumptionRecordVo.setRoomNumber(Optional.ofNullable(room).map(Room::getNumber).orElse("房间信息已被销毁"));
            consumptionRecordVo.setServiceItemName(Optional.ofNullable(serviceItem).map(ServiceItem::getName).orElse("服务项目信息已被销毁"));
            consumptionRecordVos.add(consumptionRecordVo);
        });
        return getDataTable(consumptionRecordVos);
    }

    /**
     * 导出消费记录列表
     */
    @RequiresPermissions("system:consumption:export")
    @Log(title = "消费记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(ConsumptionRecord consumptionRecord)
    {
        List<ConsumptionRecord> list = consumptionRecordService.selectConsumptionRecordList(consumptionRecord);
        ExcelUtil<ConsumptionRecord> util = new ExcelUtil<ConsumptionRecord>(ConsumptionRecord.class);
        return util.exportExcel(list, "消费记录数据");
    }

    /**
     * 新增消费记录
     */
    @GetMapping("/add")
    public String add(ModelMap mmap)
    {
        mmap.put("rooms", roomService.selectRoomList(new Room()));
        mmap.put("serviceItems", serviceItemService.selectServiceItemList(new ServiceItem()));
        mmap.put("guests", guestService.selectGuestList(new Guest()));
        return prefix + "/add";
    }

    /**
     * 新增保存消费记录
     */
    @RequiresPermissions("system:consumption:add")
    @Log(title = "消费记录", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(ConsumptionRecord consumptionRecord)
    {
        consumptionRecord.setCreatedTime(DateUtils.getNowDate());
        consumptionRecord.setUpdatedTime(DateUtils.getNowDate());
        return toAjax(consumptionRecordService.insertConsumptionRecord(consumptionRecord));
    }

    /**
     * 修改消费记录
     */
    @RequiresPermissions("system:consumption:edit")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        ConsumptionRecord consumptionRecord = consumptionRecordService.selectConsumptionRecordById(id);
        mmap.put("consumptionRecord", consumptionRecord);
        mmap.put("rooms", roomService.selectRoomList(new Room()));
        mmap.put("serviceItems", serviceItemService.selectServiceItemList(new ServiceItem()));
        mmap.put("guests", guestService.selectGuestList(new Guest()));
        return prefix + "/edit";
    }

    /**
     * 计算消费总价
     * @param serviceTotalPriceDTO
     * @return
     */
    @PostMapping("/getServiceItemTotalPrice")
    @ResponseBody
    public AjaxResult getServiceItemTotalPrice(ServiceTotalPriceDTO serviceTotalPriceDTO) {
        Long custmerId = serviceTotalPriceDTO.getCustmerId();
        String roomNumber = serviceTotalPriceDTO.getRoomNumber();
        Room room = new Room();
        room.setNumber(roomNumber);
        List<Room> rooms = roomService.selectRoomList(room);
        Room room1 = rooms.get(0);

        LambdaQueryWrapper<ConsumptionRecord> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(ConsumptionRecord::getServiceItemId, ConsumptionRecord::getQuantity, ConsumptionRecord::getTotalPrice);
        queryWrapper.eq(ConsumptionRecord::getRoomId, room1.getId());
        queryWrapper.eq(ConsumptionRecord::getCustmerId, custmerId);
        List<ConsumptionRecord> consumptionRecords = consumptionRecordService.getBaseMapper().selectList(queryWrapper);
        List<ItemVo> itemVoList = new ArrayList<>();
        consumptionRecords.forEach(i -> {
            Long serviceItemId = i.getServiceItemId();
            ServiceItem serviceItem = serviceItemService.selectServiceItemById(serviceItemId);
            itemVoList.add(ItemVo.builder()
                    .price(serviceItem.getPrice().intValue())
                    .quantity(i.getQuantity().intValue())
                    .serviceItemName(serviceItem.getName())
                    .build());
        });
        //计算总价
        Long totalPrice = consumptionRecords.stream()
                .mapToLong(ConsumptionRecord::getTotalPrice)
                .sum();
        return AjaxResult.success(ServiceItemTotalPriceVo.builder()
                .itemVoList(itemVoList)
                .totalPrice(totalPrice.intValue())
                .build());
    }

    /**
     * 修改保存消费记录
     */
    @RequiresPermissions("system:consumption:edit")
    @Log(title = "消费记录", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(ConsumptionRecord consumptionRecord)
    {
        consumptionRecord.setUpdatedTime(DateUtils.getNowDate());
        return toAjax(consumptionRecordService.updateConsumptionRecord(consumptionRecord));
    }

    /**
     * 删除消费记录
     */
    @RequiresPermissions("system:consumption:remove")
    @Log(title = "消费记录", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(consumptionRecordService.softDeleteConsumptionRecordByIds(ids));
    }
}
